package com.ygxsk.carhome.views;

import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.Gravity;
import android.widget.EditText;

import com.blankj.utilcode.util.ToastUtils;

/**
 * Created by itchenqi on 2018/5/3 0003.
 * description：监听输入内容是否超出最大长度，并设置光标位置
 */
public class MaxLengthWatcher implements TextWatcher {

    private int maxLen = 0;
    private EditText editText = null;
    private String toastMessage;

    public MaxLengthWatcher(int _maxLen, EditText _editText, String _toastMessage) {
        this.maxLen = _maxLen;
        this.editText = _editText;
        this.toastMessage = _toastMessage;
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        //  Auto-generated method stub
    }

    @Override
    public void afterTextChanged(Editable s) {
        //  Auto-generated method stub
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        //  Auto-generated method stub
        if (editText != null) {

            Editable editable = editText.getText();
            int len = editable.length();

            if (len > maxLen) {

                int selEndIndex = Selection.getSelectionEnd(editable);
                String str = editable.toString();
                //截取新字符串
                String newStr = str.substring(0, maxLen);
                editText.setText(newStr);
                editable = editText.getText();

                //新字符串的长度
                int newLen = editable.length();
                //旧光标位置超过字符串长度
                if (selEndIndex > newLen) {
                    selEndIndex = editable.length();
                }
                //设置新光标所在的位置
                Selection.setSelection(editable, selEndIndex);

                //CommUtils.displayToastShort(Utils.getApp(), "文本不能超出"+maxLen+"个字");
                ToastUtils.make().setGravity(Gravity.CENTER, 0, 0);
                //ToastUtils.showShort("文本不能超出"+maxLen+"个字");
                ToastUtils.showShort(toastMessage);
            }
        }


    }


}
